package com.swt.draw.controller;

import com.alibaba.fastjson.JSONObject;
import com.swt.draw.dao.RoleLimitMapper;
import com.swt.draw.dao.RoleMapper;
import com.swt.draw.entity.Admin;
import com.swt.draw.entity.Role;
import com.swt.draw.entity.RoleLimit;
import com.swt.draw.example.RoleExample;
import com.swt.draw.example.RoleLimitExample;
import com.swt.draw.vo.BaseResponse;
import com.swt.draw.vo.LayTableResponseVO;
import com.swt.draw.vo.RoleDetailVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName
 * @Description TODO
 * @Author Administrator
 * @Date 2019/8/31 0031 13:29
 * @Version 1.0
 **/
@RestController
@RequestMapping("/roleManager")
public class RoleController {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleLimitMapper roleLimitMapper;

    /**
     * @Author ZPF
     * @Description 添加角色
     * @Date 11:14 2019/9/1 0001
     * @Param [role]
     * @return com.swt.draw.vo.BaseResponse
     **/
    @PostMapping("/addRole")
    public BaseResponse addRole(@RequestBody JSONObject roleData){
        BaseResponse response = new BaseResponse();
        try {
            // 获取角色信息
            Role role = JSONObject.parseObject(roleData.toJSONString(), Role.class);
            // 检查角色名是否已经存在
            RoleExample example = new RoleExample();
            RoleExample.Criteria criteria = example.createCriteria();
            criteria.andRoleNameEqualTo(role.getRoleName());
            List<Role> roles = roleMapper.selectByExample(example);
            if(roles != null && roles.size() > 0){
                response.setDesc("角色名称已存在");
                return response;
            }
            // 分配角色编号
            String roleNo = new StringBuffer("role_").append(UUID.randomUUID()).toString();
            role.setRoleNo(roleNo);
            role.setRoleCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            role.setRoleCreateBy(((Admin)SecurityUtils.getSubject().getPrincipal()).getAdminNo());
            if(role.getRoleStatus() == null){
                role.setRoleStatus((short) 1);
            }
            roleMapper.insertSelective(role);
            // 获取角色分配的权限
            String roleLimit = roleData.getString("roleLimit");
            if(StringUtils.isNotEmpty(roleLimit)){
                String[] limits = roleLimit.split(",");
                for(String limit:limits){
                    RoleLimit roleLimit1 = new RoleLimit(roleNo, limit);
                    roleLimitMapper.insertSelective(roleLimit1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setCode(1001);
        response.setDesc("success");
        return response;
    }

    /**
     * @Author ZPF
     * @Description 删除角色
     * @Date 12:20 2019/9/1 0001
     * @Param []
     * @return com.swt.draw.vo.BaseResponse
     **/
    @PostMapping("/delRole")
    public BaseResponse delRole(@RequestParam(value = "roleNos[]") String[] roleNos){
        BaseResponse response = new BaseResponse();
        if(roleNos == null || roleNos.length == 0){
            return response;
        }
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        criteria.andRoleNoIn(Arrays.asList(roleNos));
        Role role = new Role();
        role.setRoleStatus((short) 2);
        roleMapper.updateByExampleSelective(role, example);
        response.setCode(1001);
        response.setDesc("success");
        return response;
    }


    @PostMapping("/editRole")
    public BaseResponse editRole(@RequestBody JSONObject roleData){
        BaseResponse response = new BaseResponse();
        Role role = JSONObject.parseObject(roleData.toJSONString(), Role.class);
        // 检查角色名称是否冲突
        RoleExample exampleCheck = new RoleExample();
        RoleExample.Criteria criteriaCheck = exampleCheck.createCriteria();
        criteriaCheck.andRoleNameEqualTo(role.getRoleName());
        List<Role> checkRoles = roleMapper.selectByExample(exampleCheck);
        if(checkRoles != null){
            for(Role item:checkRoles){
                if(!item.getRoleNo().equals(role.getRoleNo())){
                    // 角色名称冲突
                    response.setDesc("角色名称冲突");
                    return response;
                }
            }
        }
        // 保存角色信息
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        criteria.andRoleNoEqualTo(role.getRoleNo());
        roleMapper.updateByExampleSelective(role, example);
        String limits = roleData.getString("roleLimit");
        String[] limit = limits.split(",");
        // 删除原来的权限
        RoleLimitExample roleLimitExample = new RoleLimitExample();
        RoleLimitExample.Criteria criteria1 = roleLimitExample.createCriteria();
        criteria1.andRoleLimitRoleNoEqualTo(role.getRoleNo());
        roleLimitMapper.deleteByExample(roleLimitExample);
        // 重新添加关系
        for(String item: limit){
            RoleLimit roleLimit = new RoleLimit(role.getRoleNo(), item);
            roleLimitMapper.insertSelective(roleLimit);
        }
        response.setCode(1001);
        response.setDesc("success");
        return response;
    }

    /**
     * @Author ZPF
     * @Description 获取角色列表
     * @Date 13:33 2019/8/31 0031
     * @Param [role, page, limit]
     * @return com.swt.draw.vo.BaseResponse
     **/
    @RequestMapping("/getRoleList")
    public LayTableResponseVO<RoleDetailVO> getRoleList(Role role, Integer page, Integer limit){
        LayTableResponseVO response = new LayTableResponseVO();
        if(page == null){
            page = 1;
        }
        if(limit == null){
            limit = 10;
        }
        Integer start = (page - 1) * limit;
        Integer end = page * limit;
        List<RoleDetailVO> roleDetailVOS = roleMapper.getRoleWithLimit(role, end, start);
        Long count = roleMapper.getRoleCount();
        response.setData(roleDetailVOS);
        response.setCount(count);
        response.setCode(1001);
        response.setMsg("success");
        return response;
    }
}
